<template>
  <el-button plain type="primary" @click="openFormVuisible">添加账号</el-button>

  <el-table
    :data="tableData"
    row-key="id"
    style="width: 100%; margin-top: 30px"
    :header-cell-style="{
      background: '#f8f8f9',
      height: '60px',
      color: '#000000',
    }"
  >
    <el-table-column prop="id" label="账号编号" width="160" />
    <el-table-column prop="account" label="账号" width="200" />
    <el-table-column prop="phone" label="电话" width="200" />
    <el-table-column prop="name" label="账号昵称" width="200" />
    <el-table-column prop="roleName" label="账号角色" width="200" />
    <el-table-column prop="createdAt" label="创建时间" width="300" />
    <el-table-column prop="operate" label="操作">
      <template #default="scope">
        <el-button type="primary" size="small" @click="openVisbile(scope.row)"
          >编辑</el-button
        >

        <el-popconfirm
          title="你确定要删除吗?"
          @confirm="deleteUserBtn(scope.row)"
        >
          <template #reference>
            <el-button type="danger" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin-top: 20px; display: flex; justify-content: flex-end">
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />
  </div>

  <el-dialog v-model="dialogFormVisible" title="设置账号" width="500">
    <el-form :model="form" :rules="rules" ref="ruleForm">
      <el-form-item label="账号" :label-width="formLabelWidth" prop="account">
        <el-input
          v-model="form.account"
          autocomplete="off"
          :disabled="isChange"
        />
      </el-form-item>

      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input
          v-model="form.password"
          autocomplete="off"
          type="password"
          show-password
        />
      </el-form-item>

      <el-form-item label="昵称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>

      <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
        <el-input type="number" v-model="form.phone" autocomplete="off" />
      </el-form-item>

      <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
        <el-input
          type="number"
          :min="1"
          :max="1000"
          v-model.number="form.age"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item label="地址" :label-width="formLabelWidth" prop="address">
        <el-input v-model="form.address" autocomplete="off" />
      </el-form-item>

      <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio value="male">男</el-radio>
          <el-radio value="female">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="角色" :label-width="formLabelWidth" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请分配角色">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="!isChange" type="primary" @click="submitForm"
          >创建</el-button
        >
        <el-button v-if="isChange" type="primary" @click="submitForm"
          >修改</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useUserStore } from "@/stores/model/user";
import { useRoleStore } from "@/stores/model/role";
import { ElMessage } from "element-plus";

const currentPage = ref(1);
const pageSize = ref(10);
const tableData = ref([]);
const roles = ref([]);
const isChange = ref(false);
const selectUserId = ref(-1);

const userStore = useUserStore();
const roleStore = useRoleStore();

const dialogFormVisible = ref(false);
const formLabelWidth = "80px";
const ruleForm = ref(null);
const form = reactive({
  account: "",
  password: "",
  roleId: "",
  name: "",
  phone: "",
  age: 0,
  address: "",
  gender: "male",
});

const rules = reactive({
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
  name: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的11位手机号码",
      trigger: "blur",
    },
  ],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 1000,
      message: "请输入合理的年龄（1-1000岁）",
      trigger: "blur",
    },
  ],
  address: [
    { required: true, message: "请输入地址", trigger: "blur" },
    { min: 3, max: 150, message: "长度在 3 到 150 个字符", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
});

const init = async () => {
  const res = await userStore.getUserList(currentPage.value, pageSize.value);
  if (res) tableData.value = res;
};

onMounted(async () => {
  await init();
  const role = await roleStore.getAllRole();
  if (role) roles.value = roleStore.allRole;
});

const submitForm = () => {
  ruleForm.value.validate(async (valid) => {
    if (valid) {
      const res = isChange.value
        ? await userStore.updateUser(selectUserId.value, form)
        : await userStore.createUser(form);
      if (res) {
        ElMessage({
          message: isChange.value ? "修改成功" : "创建成功",
          type: "success",
        });
        dialogFormVisible.value = false;
        await init();
        form.account = "";
        form.password = "";
        form.roleId = "";
        form.name = "";
        form.phone = "";
        form.age = 0;
        form.address = "";
        form.gender = "male";
        selectUserId.value = -1;
      }
    }
  });
};

const openVisbile = (row) => {
  dialogFormVisible.value = true;
  isChange.value = true;

  selectUserId.value = row.id;
  form.account = row.account;
  form.password = row.password;
  form.roleId = row.roleId;
  form.name = row.name;
  form.phone = parseInt(row.phone);
  form.age = row.age;
  form.address = row.address;
  form.gender = row.gender;
};

const deleteUserBtn = async (row) => {
  const res = await userStore.deleteUser(row.id);
  if (res) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    await init();
  }
};

const openFormVuisible = () => {
  isChange.value = false;
  dialogFormVisible.value = true;
};

const handlePageChange = (page) => {
  currentPage.value = page;
};

const handleSizeChange = (size) => {
  pageSize.value = size;
};
</script>

<style scoped></style>
